package com.hdoit.apollo.web.wechat.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.billing.model.Billing;
import com.hdoit.apollo.logical.billing.service.IBillingService;
import com.hdoit.apollo.logical.shop.model.Address;
import com.hdoit.apollo.logical.shop.model.Customer;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.service.IAddressService;
import com.hdoit.apollo.logical.shop.service.ICustomerService;
import com.hdoit.apollo.logical.shop.service.IShopService;
import com.hdoit.apollo.logical.viewmodel.billing.BillingSearch;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.webpage.web.base.BaseWebpage;
import com.tennetcn.webpage.web.component.annotation.WebpageAuthMode;
import com.tennetcn.webpage.web.enums.WebpageAuthEnum;


@Controller
@RequestMapping(value = "/wechat/order/")
@WebpageAuthMode(validMode =WebpageAuthEnum.tryWechatAuth)
public class OrderController extends BaseWebpage{

	@Override
	public String getRoutePath() {
		
		return "areas/wechat/order/";
	}

	@Autowired
	private IBillingService billingService;
	
	@Autowired
	private ICustomerService customerService;
	
	@Autowired
	private IAddressService addressService;
	
	@Autowired
	private IShopService shopService;
	
	private final String orderListViewName="orderList";
	private final String outputViewName="output";
	private final String detailViewName="orderDetail";
 
	private final String customerViewName="customer";
	private final String shopInfoViewName="shopInfo";
	
	private final String saveViewName="save";
	
	@RequestMapping(value = saveViewName, method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8")
    public @ResponseBody String save(Model model,String customerTel,String address,String customerName,String customerId,String shopId){
    	Customer customered=customerService.queryCustomerInfoByCustomerId(customerId);
    	if (!StringUtils.isEmpty(customered)) {
    		if (!StringUtils.isEmpty(customerName)) {
    			customered.setCustomerName(customerName);
			}
    		if (!StringUtils.isEmpty(customerTel)) {
    			customered.setCustomerTel(customerTel);
			}
		}
    	if (!StringUtils.isEmpty(address)) {
    		
			List<Address> addressList=addressService.queryListMPByShopId(customerId);
			
			if (addressList.size()>0) {
				for (Address address2 : addressList) {
						address2.setModelStatus(ModelStatus.update);
				}
			}
			
			Address addressed=new Address();
			addressed.setAddress(address);
			addressed.setAddressId(CommonUtils.getKeyId());
			addressed.setCustomerId(customerId);
			addressed.setCreateDate(DateUtils.getCurrent());
			if (!StringUtils.isEmpty(shopId)) {
				addressed.setShopId(shopId);
			}
			addressed.setDeleteMark(YesOrNoInteger.no);
			addressed.setModelStatus(ModelStatus.add);
			addressList.add(addressed);
			System.err.println("莱美？");
			
			List<Address> adsList=new ArrayList<Address>();
			
			HashMap<String, Address> map=new HashMap<String, Address>();
			
			for (Address ads : addressList) {
				String id=ads.getAddress();
				if (!map.containsKey(id)) {
					map.put(id, ads);
				}
				
			}
			
			Iterator<Entry<String, Address>> iter = map.entrySet().iterator();
			while (iter.hasNext()) {
				adsList.add(iter.next().getValue());
			}
			
			addressService.applyChanges(adsList);
			
		}
    	customered.setModelStatus(ModelStatus.update);
        if(customerService.applyChange(customered)){
        	return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }else{
        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }

    }
	
	@RequestMapping(value = shopInfoViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String shopInfo(Model model,String shopId){
		System.err.println(shopId+"店铺?");
      	
    	Shop shop=shopService.queryModel(shopId);
    	model.addAttribute("shop", shop);
        return view(shopInfoViewName);
    } 
 
	@RequestMapping(value = customerViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String customer(Model model,String customerId){
		System.err.println(customerId+"客户?");
      	Customer customer=customerService.queryCustomerInfoByCustomerId(customerId);
      	List<Address> addresses=customer.getAddresses();
      	String address=addresses.get(0).getAddress();
    	Shop shop=shopService.queryModel(customer.getShopId());
    	model.addAttribute("shop", shop);
    	model.addAttribute("customer", customer);
    	model.addAttribute("address", address);
        return view(customerViewName);
    }
	 
	@RequestMapping(value = detailViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String orderDetail(Model model,String billingId){
      	Billing billing=billingService.getBillingByKey(billingId);
    	Shop shop=shopService.queryModel(billing.getShopId());
    	model.addAttribute("shop", shop);
    	model.addAttribute("billing", billing);
        return view(detailViewName);
    }
	 
	@RequestMapping(value = orderListViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String orderList(Model model,String shopId,String customerId,String pageIndex,String pageSize ,String searchKey,boolean ajaxPost){

		System.err.println(shopId+"xxxxx"+customerId);
    	Shop shop=shopService.queryModel(shopId);
    	BillingSearch search=new BillingSearch();
    	search.setShopId(shopId);
    	
    	
    	if (!StringUtils.isEmpty(searchKey)) {
			search.setSearchKey(searchKey);
		}
    	if (StringUtils.isEmpty(pageIndex)) {
    		pageIndex="1";
		}
    	if (StringUtils.isEmpty(pageSize)) {
    		 pageSize="20";
		}
    	PagerModel pagerModel=null;
    	if(pageSize!=""){
    		pagerModel = new PagerModel(Integer.parseInt(pageSize), Integer.parseInt(pageIndex));
    	}else{
    		pagerModel=new PagerModel();
    		pagerModel.setPageSize(20);
    	}
    	if (StringUtils.isEmpty(shopId)) {
    		search.setShopId(shopId);
		}
    	if (!StringUtils.isEmpty(customerId)) {
    		search.setCustomerId(customerId);
		}
    	
    	List<Billing> billings=billingService.queryListMPForWeChat(search,pagerModel);
    	
		model.addAttribute("billings", billings);
		model.addAttribute("shop", shop);
		if(ajaxPost){
             return view(outputViewName);
         }
        return view(orderListViewName);
    }
}
